package com.rtsapp.server.logger.appender;

import com.rtsapp.server.logger.format.StackTrace;
import com.rtsapp.server.logger.spi.LogLog;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 同步日志类
 *   1.SyncLoggerAppender 必须是线程安全的
 *   2.目前实现使用的是锁, 性能上不是太好，但由于该线程库本身就是为异步日志而设计的，所以暂时不做优化
 */
public class SyncLoggerAppender<T> implements ILoggerAppender<T> {


    private final ReentrantLock lock = new ReentrantLock();

    /**
     * 真正的appernder
     */
    private final ILoggerAppender<T> appender;


    public SyncLoggerAppender(ILoggerAppender<T> logger) {
        this.appender = logger;
    }


    @Override
    public void appendLog(T log) {

        try {
            lock.lockInterruptibly();
        } catch (InterruptedException e) {
            LogLog.error( "lock.lockInterruptibly 被中断, 一条日志被丢弃:" + log.toString(), e );
            return;
        }

        try{
            appender.appendLog( log );
        }finally {
            lock.unlock();
        }

    }

    @Override
    public void close() {
        appender.close();
    }


}
